// index.js
// 获取应用实例
const app = getApp()



Page({
  data: {
    current: 0,
    currentIndex: 0,
    isfromMask: false,
    issuccessMask: false,
    checked: false,
    ischecked: false,
    isCheck: false,
    isccontractMak: false,
    isloadcomplete: true,
    isonLoad: true,
    islookbohui: false,
    isjiedanjianli: false,
    ishseji:false,


    isplone: false,
    isheadimage: false,
  


  },

  biadhideLoginse() {

    wx.setStorageSync('isLogin', 2)
    app.globalData.isLogin = 2
    this.setData({
      isplone: false
    })
  },



  // 授权手机号
  bindgetphonenumber(e) {
    console.log(e)
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.showLoading({
        title: '加载中。。。', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let t = this
      wx.request({
        url: app.globalData.Interfaceurl + 'grantWxMobile',
        method: "post",
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          userId: app.globalData.userId,
        },
        success: res => {
          console.log(res)
          wx.hideLoading();
          if (res.data.result == -1) {
            wx.showToast({
              title: res.data.message,
              duration: 2500, //持续的时间
              icon: 'none', //图标
            })
          } else {
            t.setData({
              isplone: false,
              isheadimage: true
            })

          }

        },
        fail: err => {
          wx.showToast({
            title: '授权失败',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }
      })
    } else {
      wx.setStorageSync('isLogin', 2)
      app.globalData.isLogin = 2
      this.setData({
        isplone: false
      })

    }


  },



  // 授权头像
  async bindchooseavatar(e) {


    let urls = await this.upload([e.detail.avatarUrl])
    let url = app.globalData.Imageurl + urls[0]


    this.updateUserInfo(url)
  },


  // 上传附件
  upload(arr) {
    return new Promise((reslove, reject) => {
      if (arr.length == 0) {
        reslove([])
        return
      }
      wx.showLoading({
        title: '上传中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let finishFilesList = []
      arr.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.Interfaceurl + 'saveFileUpload',
          filePath: item,
          name: 'file',
          formData: {
            userId: app.globalData.userId,

          },
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            finishFilesList.push(JSON.parse(res.data).fileUrl)
            if (index >= arr.length - 1) {
              setTimeout(()=>{
                wx.hideLoading();
                reslove(finishFilesList)
               },500)
            }
          },
          fail: err => {
            return err
          }
        })
      })
    })


  },
  updateUserInfo(wxHeadImage) {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'updateUserInfo',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        wxHeadImage: wxHeadImage
      },
      success: res => {
        wx.hideLoading();


        if (res.data.result == 0) {

          t.getuserinfofun()
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }





      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
            icon: 'none', //图标
        })
      }
    })
  },
  getuserinfofun() {
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getUserInfo',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId
      },
      success(res) {
        console.log(res)
        wx.hideLoading()

        if (res.data.result == 0) {
          app.globalData.identity = res.data.user.identity
          app.globalData.mobile = res.data.user.mobile
          app.globalData.id = res.data.user.id
          app.globalData.name = res.data.user.name
          wx.setStorageSync('isLogin', true)
          app.globalData.isLogin = true
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }
        wx.setStorageSync('istab', true)
        wx.reLaunch({
          url: "/pages/index/index"
        })
      }
    })
  },






 
  // 驳回
  gobohui() {
    if (this.data.checkList.length != 0) {
      wx.navigateTo({
        url: '/pages/projectDetails/projectDetails?todo=chenkacceptance&orderId=' + this.data.checkList[0].id,
      })
    } else if (this.data.orderList.length != 0) {
      wx.navigateTo({
        url: '/shopowner/pages/previewOrder/previewOrder?todo=rejected&orderId=' + this.data.orderList[0].id,
      })
    }else if(this.data.deliverList.length != 0){
      wx.navigateTo({
        url: '/pages/projectDetails/projectDetails?todo=delivery&orderId=' + this.data.deliverList[0].id,
      })
    }
    else{
      app.globalData.tabindex=1
      wx.setStorageSync('wagon', 2)
      wx.switchTab({
        url: '/pages/project/project',
      })
    }
  },


  
  // 岩板砖家派单
  bindsupdispatch(e) {

    if(this.data.dispatchList.length==0&&this.data.tomorrowOverdueList.length!=0){
      app.globalData.tabindex=2
      wx.setStorageSync('wagon', 2)
     wx.switchTab({
       url: '/pages/project/project',
     })
    }else{
     wx.navigateTo({
       url: '/pages/projectDetails/projectDetails?todo=dispatch&&orderId=' + this.data.dispatchList[0].id,
     })
    }
 
   },
  Hideookbohui() {
    this.setData({
      islookbohui: false,
      isjiedanjianli: false,
      ishseji:false
    })

  },
  hideisfromMask() {
    this.setData({
      isfromMask: false,
      isccontractMak: false
    })
  },
  // 图片预览
  priview(e) {
    let urls = e.currentTarget.dataset.urls.map(item => this.data.Imageurl + item)
    let current = e.currentTarget.dataset.current
    wx.previewImage({
      urls: urls,
      current: current
    })
  },
  // 品牌咨询
  gobrandConsulting() {

    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/brandConsulting/brandConsulting',
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }



  },

  goserviceTeam(e) {

    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/serviceTeam/serviceTeam?index=' + e.currentTarget.dataset.index,
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  // 实景案例详情
  bindcase(e) {
    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/realCasedetail/realCasedetail?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  // 确认接单
  bindSubmit() {
    this.setData({
      isfromMask: false,
      isccontractMak: true,

    })

  },
  // 同意接单
  bindAgree() {
    if (!this.data.ischecked) {
      wx.showToast({
        title: '请勾选协议',
        duration: 2500, //持续的时间
            icon: 'none', //图标
      })
      return
    }
    this.saveReceiveOrder()
  },
  // 隐藏成功接单遮罩层
  HidesuccessMask() {
    this.setData({
      issuccessMask: false,
      isCheck: false,
      ischecked: false
    })
    this.getWaitReceiveByBricklay()
      .then(res => {
        if (res.id) {
          this.setData({
            isfromMask: true,
            orderId: res.id,
            yeahcProjectOrder: res,
            token: app.token()
          })
          this.getOrderDetails(res.id)
        }
      })
  },

  // 拒绝接单
  bindRefused() {
    let ischecked = this.data.ischecked
    this.setData({
      isccontractMak: false,
      ischecked: false,
      isCheck: !ischecked
    })
  },
  // 滑动录播图
  bindchange(e) {
    if (this.data.current == 0 && this.data.currentIndex > 1) { //卡死时，重置current为正确索引
      this.setData({
        current: this.data.currentIndex
      });
    } else { //正常轮转时，记录正确页码索引
      this.setData({
        currentIndex: e.detail.current
      })
    }

  },
  // 全民监工
  goOverseer() {

    // 判断是否有登录
    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/overseer/overseer',
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  // 全民监工项目详情
  gositeDetail(e) {

    // 判断是否有登录
    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/siteDetails/siteDetails?orderId=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  // 实景案例
  goScace() {

    // 判断是否有登录
    if (app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/realCase/realCase',
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  //勾选 合同
  bindChecked() {
    let ischecked = this.data.ischecked
    this.setData({
      ischecked: !ischecked
    })
  },





  // 31.瓦工待接单项目
  getWaitReceiveByBricklay() {
    let t = this
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '加载中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      wx.request({
        url: app.globalData.Interfaceurl + 'getWaitReceiveByBricklay',
        method: "post",
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data: {
          userId: app.globalData.userId,

        },
        success: res => {
          wx.hideLoading();
          // console.log(res)
          if (res.data.yeahcProjectOrder.id) {
            resolve(res.data.yeahcProjectOrder)
          } else {
            resolve('')
          }
        },
        fail: err => {
          wx.showToast({
            title: '请求失败',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }
      })
    })



  },



  // 31.14.被驳回的项目列表
  getRebutOrderList() {
    let t = this
    wx.showLoading({
      title: '加载中...', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getRebutOrderList',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,

      },
      success: res => {
        wx.hideLoading();
        if (res.data.orderList.length != 0 || res.data.checkList.length != 0|| res.data.tomorrowOverdueList.length != 0||res.data.deliverList.length!=0) {
          t.setData({
            orderList: res.data.orderList,
            checkList: res.data.checkList,
            tomorrowOverdueList:res.data.tomorrowOverdueList,
            deliverList:res.data.deliverList,
            islookbohui: true
          })
        } else {
          this.setData({
            islookbohui: false
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })



  },
  getDeliverCheckOrderList() {
    let t = this
    wx.showLoading({
      title: '加载中...', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getDeliverCheckOrderList',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,

      },
      success: res => {
        wx.hideLoading();
        if (res.data.dispatchList.length != 0 || res.data.tomorrowOverdueList.length != 0) {
          t.setData({
            dispatchList: res.data.dispatchList,
            tomorrowOverdueList:res.data.tomorrowOverdueList,
            isjiedanjianli: true
          })
        } else {
          this.setData({
            isjiedanjianli: false
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })



  },

  // 18.项目详情
  getOrderDetails(orderId) {
    let t = this
    wx.showLoading({
      title: '加载中...', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getOrderDetails',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        orderId: orderId
      },
      success: res => {
        wx.hideLoading();
        t.setData({
          projectOrder: res.data.projectOrder,
          designList: res.data.designList,
          deliverList: res.data.deliverList,
          buildList: res.data.buildList,
          shopowner: res.data.shopowner,
          supervise: res.data.supervise,
          bricklay: res.data.bricklay,
          designer: res.data.designer,
          Imageurl: app.globalData.Imageurl,

        })
        if(t.data.yeahcProjectOrder&&t.data.yeahcProjectOrder.workId){
          let workObj=res.data.workList.filter(item=>item.id==t.data.yeahcProjectOrder.workId)
          t.setData({
            workObj:workObj[0]
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },





  // 32.瓦工接单
  saveReceiveOrder() {
    let t = this
    wx.showLoading({
      title: '加载中...', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'saveReceiveOrder',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        token: t.data.token,
        workId: t.data.yeahcProjectOrder.workId
      },
      success: res => {
        wx.hideLoading();
        if (res.data.result != -1) {
          t.setData({
            isccontractMak: false,
            issuccessMask: true
          })
        } else {
          wx.showToast({
            title: res.data.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }

      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },
  // 获得首页数据
  getHomePage(orderId) {
    let t = this
    wx.showLoading({
      title: '加载中...', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getHomePage',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId
      },
      success: res => {
        console.log(res)
        wx.hideLoading();
        t.setData({
          homeBanner: res.data.homeBanner,
          overseerList: res.data.overseerList,
          realCaseList: res.data.realCaseList,
          brandInformation: res.data.brandInformation,
          isonLoad: false,
        })

      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },


 // 设计师项目列表
 getWaitItem() {
  let t = this
  wx.showLoading({
    title: '加载中...', //提示的内容
    mask: true //显示透明蒙层 防止触摸穿透
  })
  wx.request({
    url: app.globalData.Interfaceurl + 'getWaitItem',
    method: "post",
    header: {
      "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
    },
    data: {
      userId: app.globalData.userId,
    },
    success: res => {
      console.log()
      wx.hideLoading()
      console.log(res.data.waitItem.length)
  if(res.data.waitItem.length!=0){
    t.setData({
      ishseji:true,
      orderId:res.data.waitItem[0].id,
      waitItemRecordId:res.data.waitItem[0].waitItemRecordId
    })
  }else{
    t.setData({
      ishseji:false
    })
  }
     
    },
    fail: err => {
      wx.showToast({
        title: '请求失败',
        duration: 2500, //持续的时间
            icon: 'none', //图标
      })
    }
  })
},
  // 86.读取待办事项
  readWaitItem() {
    let t = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.Interfaceurl + 'readWaitItem',
        method: "post",
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data: {
          waitItemRecordId: t.data.waitItemRecordId,

        },
        success: res => {
          wx.hideLoading()
          resolve("ok")

        },
        fail: err => {
          wx.showToast({
            title: '请求失败',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }
      })
    })
  },
bindsheji(){

  wx.setStorageSync('istab', true)
  let  todo = 'design'
  this.readWaitItem().then((res => {
    wx.navigateTo({
      url: '/shopowner/pages/previewOrder/previewOrder?todo=' + todo + '&&orderId=' + this.data.orderId,
    })
  }))

},
bindtemp(){},
  onLoad() {
    wx.setStorageSync('istab', false)
 
    app.wxlogin()
      .then(res => {
        // if(app.globalData.identity==4||app.globalData.identity==5||app.globalData.identity==8||app.globalData.identity==10){
        //     wx.switchTab({
        //       url: '/pages/project/project',
        //     })
        // }


        this.setData({
          isloadcomplete: false,
          Imageurl: app.globalData.Imageurl,
          userwximage: app.globalData.Imageurl+'/resource/userfiles/shunhui/user_grant_image.png'
        })
        let myTab = this.selectComponent('#myTab'); // 页面获取自定义组件实例
        myTab.gettabList(); // 通过实例调用组件事件
        this.getHomePage()



        if (app.globalData.identity == 6) {
          this.getWaitReceiveByBricklay()

            .then(res => {
              if (res.id) {
                this.setData({
                  isfromMask: true,
                  yeahcProjectOrder: res,
                  orderId: res.id,
                  token: app.token()
                })
                this.getOrderDetails(res.id)
              }
            })
        }


        if (app.globalData.identity == 5) {
          this.getRebutOrderList()
        }
        if (app.globalData.identity == 4) {
          this.getDeliverCheckOrderList()
        }

        if (app.globalData.identity == 8) {
          this.getWaitItem()
        }

        if (wx.getStorageSync('isLogin') == true) {
          this.setData({
            isplone: false
          })
        } else {
          this.setData({

            isplone: true
          })
        }
      })




    // this.setData({
    //   isloadcomplete: false,
    //   identity:app.globalData.identity,
    // })

    // if(app.globalData.identity==1){
    //     this.setData({
    //         isOrderMask:true
    //     })
    // }

  },
  onShow() {
    wx.onAppShow(function (res) {
      console.log(res)
      // if ((res.referrerInfo && res.referrerInfo.appId == 1035) || (res.referrerInfo && res.referrerInfo.appId == "1035")) {
      //   this.getupdateUserInfo()
      // }
    })


    if (!this.data.isonLoad) {
      if (wx.getStorageSync('istab')) {


        this.setData({
          identity: app.globalData.identity,
          isfromMask:false,
          isccontractMak:false,
          issuccessMask:false,
          islookbohui:false,
          isjiedanjianli:false,
          ishseji:false,
        })

        let myTab = this.selectComponent('#myTab'); // 页面获取自定义组件实例
        myTab.gettabList(); // 通过实例调用组件事件
        this.getHomePage()
    

        if (app.globalData.identity == 6) {
          this.getWaitReceiveByBricklay()
            .then(res => {

              if (res.id) {
                this.setData({
                  isfromMask: true,
                  orderId: res.id,
                  yeahcProjectOrder: res,
                  token: app.token(),
                  isCheck: false
                })
                this.getOrderDetails(res.id)
              }
            })
        }
        if (app.globalData.identity == 5) {
          this.getRebutOrderList()
        }
        if (app.globalData.identity == 4) {
          this.getDeliverCheckOrderList()
        }
        if (app.globalData.identity == 8) {
          this.getWaitItem()
        }
      }
    }

    wx.setStorageSync('istab', false)

  },
  onShareAppMessage() {

  }
})